<template>
  <!-- 流程定义 -->
  <div>
    <el-row>
      <el-col style="margin-right: 10px" class="content-left">
        <el-row class="handleBox">
          <el-col :span="18">
            <template>
              <el-button type="normal" @click="addFunc">新增</el-button>
              <el-button type="normal" @click="editFunc">编辑</el-button>
              <el-button type="normal" @click="delFunc()">删除</el-button>
            </template>
          </el-col>
          <el-col :span="6">
            <div class="handleIconBox">
              <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="search_porper">
                  <el-form
                    ref="searchForm"
                    :model="searchForm"
                    label-width="90px"
                    label-position="left"
                    size="mini"
                  >
                    <el-form-item label="原审批人：">
                      <div class="treeBoxBig">
                        <div class="treeBox">
                          {{ searchForm.principalUser }}
                        </div>
                        <div class="treeBtnCS" @click="principalUserBtn" />
                      </div>
                    </el-form-item>
                    <!-- 人员弹窗 -->
                    <el-dialog
                      v-dialogDrag
                      title="选择"
                      :visible.sync="reassignmentVisible"
                      width="60%"
                      append-to-body
                    >
                      <reassignmentTable
                        ref="reassignmentTable"
                        @approvered="approvered"
                        @principalUser="principalUser"
                        @agentUser="agentUser"
                        @sPrincipalUser="sPrincipalUser"
                        @sAgentUser="sAgentUser"
                        @reassignClose="reassignClose"
                      />
                    </el-dialog>

                    <el-form-item label="代理人：">
                      <div class="treeBoxBig">
                        <div class="treeBox">{{ searchForm.agentUser }}</div>
                        <div class="treeBtnCS" @click="agentUserBtn" />
                      </div>
                    </el-form-item>
                    <el-form-item label="代理日期：" prop="beginDate">
                      <el-date-picker
                        v-model="searchForm.beginDate"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetime"
                        style="width: 180px"
                      />
                    </el-form-item>
                    <el-form-item label="至" prop="endDate">
                      <el-date-picker
                        v-model="searchForm.endDate"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="datetime"
                        style="width: 180px"
                      />
                    </el-form-item>
                  </el-form>
                  <div style="text-align: center; padding: 10px">
                    <el-button
                      size="mini"
                      @click="(searchForm.page = 1), searchFunc()"
                    >查询</el-button>
                    <el-button size="mini" @click="searchClear">重置</el-button>
                  </div>
                </div>
                <i slot="reference" class="iconfont icon-sousuo" title="搜索" />
              </el-popover>
              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :key="item.prop"
                      :label="item.label"
                    >{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <i
                  slot="reference"
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                />
              </el-popover>
            </div>
          </el-col>
        </el-row>

        <el-table
          ref="multipleTable"
          :data="tableData"
          @row-click="authorizeFor"
        >
          <el-table-column width="55" type="selection"  />
          <el-table-column
            v-if="columnState[0]"
            prop="principalUser"
            label="原审批人"
            show-overflow-tooltip
          />

          <el-table-column
            v-if="columnState[1]"
            prop="agentUser"
            label="代理人"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnState[2]"
            prop="beginDate"
            label="开始日期"
            sortable
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div v-if="scope.row.beginDate">
                {{ timeFormat(scope.row.beginDate) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnState[3]"
            prop="endDate"
            label="结束日期"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.endDate">
                {{ timeFormat(scope.row.endDate) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnState[4]"
            prop="agentScope"
            label="代理范围"
            :formatter="
              (row) =>
                row.agentScope.map((v) => v.processCode).toString() || '-'
            "
          />
          <el-table-column
            v-if="columnState[5]"
            prop="creator"
            label="创建人"
            :formatter="(row) => row.creator || '-'"
          />
          <el-table-column
            v-if="columnState[6]"
            prop="createdTm"
            label="创建时间"
            sortable
            :formatter="(row) => row.createdTm || '-'"
          />
        </el-table>
        <pagination
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          @refresh="searchFunc"
        />
      </el-col>
    </el-row>
    <!-- 流程代理弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="50%"
    >
      <el-form
        ref="saveForm"
        :model="saveForm"
        label-width="110px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="原审批人：" prop="principalUser">
              <el-input
                v-model="saveForm.principalUser"
                readonly
                clearable
                style="width: 70%; display: inline-block; margin-right: 10px"
              />
              <el-button
                icon="el-icon-plus"
                style="display: inline-block"
                @click="principalUserList"
              >选择</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代理人：" prop="agentUser">
              <el-input
                v-model="saveForm.agentUser"
                readonly
                clearable
                style="width: 70%; display: inline-block; margin-right: 10px"
              />
              <el-button
                icon="el-icon-plus"
                style="display: inline-block"
                @click="agentUserList"
              >选择</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="beginDate">
              <el-date-picker
                v-model="saveForm.beginDate"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                style="width: 70%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="saveForm.endDate"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                :picker-options="limitPickerOptions"
                style="width: 70%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" style="margin-top: 10px">
            <!-- <el-form-item label="代理流程"> -->

            <span
              style="color: #333; margin-right: 50px"
            ><i style="color: #ff0000">* </i>代理流程</span>
            <el-checkbox v-model="saveForm.agentAllFlag">全部</el-checkbox>
            <!-- </el-form-item> -->
          </el-col>
          <el-col :span="12">
            <!-- prop="processDefName" -->
            <el-form-item
              v-if="!saveForm.agentAllFlag"
              label=""
              prop="processDefName"
              label-width="50px"
            >
              <el-input
                v-model="saveForm.processDefName"
                readonly
                clearable
                style="width: 70%; display: inline-block; margin-right: 10px"
              />
              <el-button
                icon="el-icon-plus"
                style="display: inline-block"
                @click="processList"
              >选择</el-button>
              <!-- </el-col> -->
            </el-form-item>
          </el-col>
          <!-- 代理流程 -->
          <el-dialog
            v-dialogDrag
            title="选择"
            :visible.sync="processListVisible"
            width="50%"
            append-to-body
          >
            <process
              ref="process"
              @processed="processed"
              @processClose="processClose"
            />
          </el-dialog>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFunc">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import process from '@/views/workFlow/components/process'
import reassignmentTable from '@/views/workFlow/components/reassignmentTable'
import moment from 'moment'
import { workflow } from '@/api/index'

export default {
  components: {
    reassignmentTable,
    process
  },
  data() {
    return {
      processLists: [], // 流程集合
      processListVisible: false, // 代理流程
      reassignmentVisible: false,
      exportIcon: true,
      importIcon: true,
      addOrEdit: false, // 新增/编辑/查看弹窗
      isModuleData: false, // 同步模块数据弹窗
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveTitles: ['新增', '编辑'],
      searchForm: {
        agentUser: '',
        principalUser: '',
        beginDate: '',
        endDate: '',
        page: 1,
        size: 15
      },
      total: 0,
      saveForm: {
        agentUser: '',
        principalUser: '',
        beginDate: '',
        endDate: '',
        agentAllFlag: '',
        processDefName: ''
      },
      saveFormRules: {
        principalUser: [{ required: true, message: '请选择', trigger: 'blur' }],
        agentUser: [{ required: true, message: '请选择', trigger: 'blur' }],
        beginDate: [{ required: true, message: '请选择', trigger: 'blur' }],
        endDate: [{ required: true, message: '请选择', trigger: 'blur' }],
        processDefName: [
          { required: true, message: '请选择', trigger: 'blur' }
        ]
      },
      checkList: [],
      // 列隐藏
      textData: [
        { label: '原审批人' },
        { label: '代理人' },
        { label: '开始日期' },
        { label: '结束日期' },
        { label: '代理范围' },
        { label: '创建人' },
        { label: '创建时间' }
      ],
      // 获取table的数据
      tableData: [],
      limitPickerOptions: {
        // 日期选择器-限制范围
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      }
    }
  },
  computed: {
    columnState() {
      const arr = []
      const arr1 = this.textData
      const arr2 = this.checkList
      for (let i = 0; i < arr1.length; i++) {
        let flg = false
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true
          }
        }
        arr.push(flg)
      }
      return arr
    }
  },
  watch: {
    addOrEdit() {
      this.$nextTick(()=>{
         // 窗口打开或关闭清除校验结果
        this.$refs.saveForm.clearValidate();
      })
    }
  },
  created() {
    this.checkListInit()
    this.searchFunc()
    // this.getDict();
  },
  mounted() {},
  methods: {
    principalUserList() {
      this.reassignmentVisible = true
      setTimeout(() => {
        this.$refs.reassignmentTable.init({ id: '2' })
        this.$refs.reassignmentTable.getOrgList()
      }, 30)
    },
    agentUserList() {
      this.reassignmentVisible = true
      setTimeout(() => {
        this.$refs.reassignmentTable.init({ id: '3' })
        this.$refs.reassignmentTable.getOrgList()
      }, 30)
    },
    processList() {
      this.processListVisible = true
      setTimeout(() => {
        this.$refs.process.init()
      }, 30)
    },
    // 点击原审批人
    principalUserBtn() {
      this.reassignmentVisible = true
      setTimeout(() => {
        this.$refs.reassignmentTable.init({ id: '0' })
        this.$refs.reassignmentTable.getOrgList()
      }, 30)
    },
    // 点击代理人
    agentUserBtn() {
      this.reassignmentVisible = true
      setTimeout(() => {
        this.$refs.reassignmentTable.init({ id: '1' })
        this.$refs.reassignmentTable.getOrgList()
      }, 30)
    },
    reassignClose() {
      this.reassignmentVisible = false
    },
    approvered(val) {
      this.saveForm.agentUser = val.userName
      this.saveForm.principalUser = val.userName
      this.reassignmentVisible = false
      this.$forceUpdate()
    },
    principalUser(val) {
      this.saveForm.principalUser = val.userName
      this.reassignmentVisible = false
      this.$forceUpdate()
    },
    agentUser(val) {
      this.saveForm.agentUser = val.userName
      this.reassignmentVisible = false
    },
    sPrincipalUser(val) {
      this.searchForm.principalUser = val.userName
      this.reassignmentVisible = false
    },
    sAgentUser(val) {
      this.searchForm.agentUser = val.userName
      this.reassignmentVisible = false
    },
    processClose() {
      this.processListVisible = false
    },
    // 选择的已发布的流程
    processed(val) {
      this.saveForm.processDefName = val.map((v) => v.processDefName)
      this.saveForm.processDefName = this.saveForm.processDefName.toString()
      this.saveForm.processCodes = val.map((v) => v.processDefCode)
      this.processListVisible = false
      this.$forceUpdate()
    },
    searchClear() {
      for (const key in this.searchForm) {
        this.searchForm[key] = ''
      }
      this.searchForm.page = 1
      this.searchForm.size = 15
    },
    checkListInit() {
      this.checkList = this.textData.map((v) => {
        return v.label
      })
    },
    searchFunc() {
      const data = this.searchForm
      workflow.queryForPageProcessAgent(data).then((res) => {
        this.tableData = res.datas.rows
        this.total = res.datas.total
      })
    },
    addFunc() {
      this.saveFlg = 1
      for (let  k in this.saveForm) {
        this.saveForm[k] = ''
      }
      this.saveForm.agentScope = []
      this.addOrEdit = true
    },
    editFunc() {
      this.saveFlg = 2
      let selection = this.$refs.multipleTable.selection
      if (selection.length !== 1) {
        return this.$message.warning('请选择一条数据进行修改')
      }
      let row = selection[0]
      let form = { ...row }
      this.saveForm = Object.assign({},this.saveForm, form)
      if (this.saveForm.agentAllFlag === '0') {
        this.saveForm.agentAllFlag = false
      } else {
        this.saveForm.agentAllFlag = true
      }
      this.$forceUpdate()
      // 遍历流程编码
      let codes = this.saveForm.processCodes
      this.transferProcess(codes)
      this.addOrEdit = true
    },
    transferProcess(codes) {
      const data = {
        modelCode: '',
        modelName: '',
        status: ''
      }
      workflow.queryDefForAgent(data).then((res) => {
        if (res.code === 200) {
          this.processLists = res.datas
          var processDefName = []
          for (let i = 0; i < codes.length; i++) {
            for (let j = 0; j < this.processLists.length; j++) {
              if (codes[i] === this.processLists[j].processDefCode) {
                   processDefName.push(
                  this.processLists[j].processDefName
                )
                break
              }
            }
          }
          this.saveForm.processDefName =processDefName.toString()
        }
      })
    },
    saveFunc() {
      this.$refs['saveForm'].validate((valid) => {
        if (valid) {
          const data = {
            ...this.saveForm
          }
          if (this.saveForm.agentAllFlag) {
            data.agentAllFlag = '1'
            data.processCodes = []
          } else {
            data.agentAllFlag = '0'
          }
          workflow.saveProcessAgent(data).then((res) => {
            if (res.code === 200) {
              this.$message.success('保存成功')
              this.addOrEdit = false
              this.searchFunc()
            } else {
              this.$message.error(res.message || '保存失败')
            }
          })
        }
      })
    },
    delFunc() {
      const selection = this.$refs.multipleTable.selection
      if (selection.length < 1) {
        return this.$message.warning('请选择要删除的数据')
      }
      this.$confirm('您确定要删除选中数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const data = { ids: selection.map((v) => v.agentId) }
          workflow.removeProcessAgent(data).then((res) => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.searchFunc()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection()
      }
      this.$refs.multipleTable.toggleRowSelection(row, true)
    },
    timeFormat(val) {
      if (val) return moment(val).format('YYYY-MM-DD HH:mm:ss')
      else return ''
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.searchForm.size = val
      this.searchFunc()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.searchForm.page = val
      this.searchFunc()
    }
  }
}
</script>

<style lang="scss" scoped>
.treeBoxBig {
  width: 180px;
  height: 32px;
  border: 1px solid #dce0e6;
  border-radius: 4px;
  color: white;
  .treeBox {
    width: 140px;
    height: 32px;
    padding-left: 10px;
    line-height: 32px;
  }
  .treeBtnCS {
    background: url("~@/assets/images/popWindow_arrow.gif");
    background-repeat: no-repeat;
    height: 32px;
    width: 32px;
    position: absolute;
    left: 156px;
    top: 8px;
    cursor: pointer;
  }
}
img {
  width: 70%;
}
</style>
